const path = require('path')
const express = require('express')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const api = require('./api.js')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

const app = express()

app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

api(app)

app.get('/hello', function (req, res) {
  res.cookie('name1', 'tobi1', { httpOnly: false })
  res.cookie('name2', 'tobi2', { httpOnly: false })
  res.send('Hello World!!!')
})

app.use(express.static(resolve('./dist')))

let host = '127.0.0.1'
let port = 3000

var http = require('http').Server(app)

module.exports = {
  instance: app,
  openServer: function () {
    return new Promise(function (resolve, reject) {
      try {
        http.listen(port, function () {
          resolve()
          console.log('Example app listening at http://%s:%s', host, port)
        })
      } catch (error) {
        reject(error)
      }
    })
  },
  stopServer: function () {
    return new Promise(function (resolve, reject) {
      try {
        http.close(function () {
          resolve()
          console.log('Example app stop listening at http://%s:%s', host, port)
        })
      } catch (error) {
        reject(error)
      }
    })
  }
}
